 <!--
* description: 区域仓库城市仓库关系维护
* author: duanhy
* createdDate: 2020-12-5
-->
<template>
  <section class="app-container app-container-table">
    <div id="TreeTable">
      <!--树形区域-->
      <el-aside class="el-slide">
        <el-input
          v-model="filterText"
          placeholder="输入关键字进行过滤"
        />
        <el-tree
          ref="tree"
          :expand-on-click-node="false"
          default-expand-all
          :data="menueList"
          highlight-current
          :props="defaultProps"
          :filter-node-method="filterNode"
          @node-click="handleNodeClick"
        />
      </el-aside>
      <el-main ref="mainHeight">
        <div class="hander-bg">
          <!--网格区域-->
          <one-table-template
            v-if="resetcode==='0'"
            :key="resetid"
            ref="multipleTable"
            :dynamic-buttons="tableButtons"
            :dynamic-components="tableComponents"
            :dynamic-api-config="apiConfig"
            :dynamic-table-cols="tableCols"
            :dynamic-form-fields.sync="formField"
            :refresh-table-key="refreshTableKey"
            :is-show-pagination="false"
          />
          <div v-if="resetcode==='1'" style="height:calc(100vh - 109px);background-color: #fff;padding:1rem">
            <one-table-template
              :key="resetid"
              ref="multipleTable1"
              :dynamic-components="tableComponents1"
              :dynamic-form-fields.sync="formField"
              :dynamic-is-show-select="false"
              :dynamic-is-init-table="false"
              :dynamic-is-column-drop="true"
            />
          </div>
          <Edit
            v-if="dialogShow"
            :is-dialog-visible="dialogShow"
            :data-for-form="editRowData"
            @close="close"
            @querymenue="querymenue"
            @areackQuery="areackQuery"
          />
        </div>
      </el-main>
    </div>
  </section>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import Edit from './edit'
import Vue from 'vue'
export default {
  name: 'RegionCity',
  components: {
    OneTableTemplate,
    Edit
  },
  filters: {},
  mixins: [oneTableWithViewTemplateMixins],
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData(
      // 同时加载当前页面和编辑框页面的配置
      to.path,
      function() {
        next()
      })
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      editRowData: '',
      filterText: '',
      resetcode: '',
      resetid: 0,
      dialogShow: false,
      // 树形结构
      menueParam: {},
      menueList: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },

      // 网格查询API配置对象
      apiConfig: {
        // APIUrl: '/mp/e3sh/vesale/basics/regionalCityWMService/findRegionCity.do'
      },
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          clickEvent: () => this.add(),
          text: '添加城市仓库',
          name: 'add',
          position: 'left',
          fuzzySearch: true
        }
      ],
      // 动态组件-查询条件
      tableComponents: this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
      this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents.length > 0
        ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents : [
          {
            compKey: 'compKey1',
            span: this.spanNum(),
            labelName: '区域仓库编码：',
            codeField: 'areaStockCode',
            isRequire: true,
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey2',
            span: this.spanNum(),
            labelName: '区域仓库名称：',
            codeField: 'areaStockName',
            isRequire: true,
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey4',
            span: this.spanNum(),
            labelName: '管理员姓名：',
            codeField: 'stockAdmin',
            isRequire: true,
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey5',
            span: this.spanNum(),
            labelName: '管理员电话：',
            codeField: 'stockAdminPhone',
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey6',
            span: this.spanNum(),
            labelName: '传真：',
            codeField: 'stockFax',
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey61',
            span: this.spanNum(),
            labelName: '邮编：',
            codeField: 'stockPostcode',
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey7',
            span: this.spanNum(),
            labelName: '省份：',
            codeField: 'provinceName',
            isRequire: true,
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey8',
            span: this.spanNum(),
            labelName: '城市：',
            codeField: 'cityName',
            isRequire: true,
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey81',
            span: this.spanNum(),
            labelName: '区县：',
            codeField: 'countyName',
            isRequire: true,
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey9',
            span: this.spanNum(),
            labelName: '详细地址：',
            codeField: 'stockAddress',
            isRequire: true,
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          // {
          //   compKey: 'compKey91',
          //   span: this.spanNum(),
          //   labelName: '所属总部仓库：',
          //   codeField: 'zbStockName',
          //   isRequire: true,
          //   disabled: true,
          //   component: () => import('@/components/org/commonInput'),
          //   type: 'inputText',
          //   isMust: true
          // },
          {
            compKey: 'compKey10',
            span: this.spanNum(),
            labelName: '启动状态：',
            codeField: 'isEnableCode',
            isRequire: true,
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey11',
            span: this.spanNum(),
            labelName: '备注：',
            codeField: 'stockRemark',
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          }
        ],
      tableComponents1: this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
      this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents.length > 0
        ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableComponents : [
          {
            compKey: 'compKey12',
            span: this.spanNum(),
            labelName: '仓库编码：',
            codeField: 'carHouseCode',
            isRequire: true,
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey13',
            span: this.spanNum(),
            labelName: '仓库名称：',
            codeField: 'carHouseName',
            isRequire: true,
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey14',
            span: this.spanNum(),
            labelName: '管理员姓名：',
            codeField: 'carHouseManager',
            isRequire: true,
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey15',
            span: this.spanNum(),
            labelName: '管理员电话：',
            codeField: 'carHouseTEL',
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey16',
            span: this.spanNum(),
            labelName: '传真：',
            codeField: 'carHouseFAX',
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey17',
            span: this.spanNum(),
            labelName: '邮编：',
            codeField: 'ZIP',
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey18',
            span: this.spanNum(),
            labelName: '省份：',
            codeField: 'provinceName',
            isRequire: true,
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey19',
            span: this.spanNum(),
            labelName: '城市：',
            codeField: 'cityName',
            isRequire: true,
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey20',
            span: this.spanNum(),
            labelName: '区县：',
            codeField: 'countyName',
            isRequire: true,
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey21',
            span: this.spanNum(),
            labelName: '详细地址：',
            codeField: 'carHouseAddr',
            isRequire: true,
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey22',
            span: this.spanNum(),
            labelName: '默认搬入地：',
            codeField: 'isDefaultAddr',
            isRequire: true,
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey26',
            span: this.spanNum(),
            labelName: '启动状态：',
            codeField: 'isEnableCode',
            isRequire: true,
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          },
          {
            compKey: 'compKey27',
            span: this.spanNum(),
            labelName: '备注：',
            codeField: 'REMARK',
            disabled: true,
            component: () => import('@/components/org/commonInput'),
            type: 'inputText',
            isMust: true
          }
        ],
      // 动态生成网格列
      tableCols: this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
      this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols.length > 0
        ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].tableCols : [
          {
            prop: 'carStockHouseId',
            label: '城市仓库ID',
            hidden: true
          },
          {
            prop: 'updateControlId',
            label: '并发ID',
            hidden: true
          },
          {
            prop: 'roleName',
            label: '操作',
            width: null,
            align: 'center',
            isComponent: true,
            comps: [
              {
                compKey: 'propKey1',
                labelName: '删除',
                align: 'center',
                codeField: 'editControlBtn',
                clickEvent: (index) => this.delete(index),
                disabled: true,
                component: () => import('@/components/org/linkButton')
              }
            ]
          },
          {
            prop: 'carStockHouseId',
            label: '城市仓库id',
            hidden: true
          },
          {
            prop: 'cityName',
            label: '城市'
          },
          {
            prop: 'carHouseName',
            label: '城市仓库名称'
          },
          {
            prop: 'isEnableCode',
            label: '启用状态'
          }
        ],
      // 表单查询数据
      formField: {
        isEnableCode: '1'
      },

      tableHeaderRowClassName({ row, rowIndex }) {
        if (rowIndex === 0) {
          return 'background-color:rgb(239, 239, 239);height:32px;'
        }
      },

      // 组件数据
      isEnableSpan: 20,
      tableButtonstype: [],
      tableColstype: []
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.tableColstype = JSON.parse(JSON.stringify(this.tableCols))
    this.tableButtonstype = JSON.parse(JSON.stringify(this.tableButtons))
  },
  mounted() {
    this.$nextTick(() => {
      this.querymenue()
    })
  },
  methods: {
    // 区域仓库详情查询
    areackQuery(id) {
      const that = this
      var dataid
      if (id) {
        dataid = id
      } else {
        dataid = that.editRowData
      }
      const queryObj = {
        // api配置
        apiConfig: { ServiceCode: 'findAMDById', APIUrl: '/mp/e3sh/vesale/basics/regionalCityWMService/findAMDById.do' },
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          pageSize: '',
          pageIndex: '',
          // 当前中台使用的名称有dataInfo、info，具体查看API文档
          dataInfo: { areaStockId: dataid }
        }
      }
      // 转换了中台请求格式数据
      var paramD = that.$getParams(queryObj)
      // 调用中台API方法（可复用）
      that.$requestAPI(paramD).then(response => {
        this.resetcode = '0'
        var obj = JSON.parse(JSON.stringify(that.formField))
        Object.assign(obj, response.rows)
        that.formField = obj
        var result = JSON.parse(JSON.stringify(response.rows).replace(/regionalCity/g, 'rows'))
        setTimeout(() => {
          that.$refs['multipleTable'].handleResponseRestful(result, 1, -1)
          that.refreshTableKey += 1
        }, 100)
        // that.queryTbale(1)
        that.resetid += 1
      })
    },
    // 城市仓库详情查询
    cityCkQuery(id) {
      const that = this
      const queryObj = {
        // api配置
        apiConfig: { ServiceCode: 'findDetailsCity', APIUrl: '/mp/e3sh/vesale/basics/regionalCityWMService/findDetailsCity.do' },
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          pageSize: '',
          pageIndex: '',
          // 当前中台使用的名称有dataInfo、info，具体查看API文档
          dataInfo: { carStockHouseId: id }
        }
      }
      // 转换了中台请求格式数据
      var paramD = that.$getParams(queryObj)
      // 调用中台API方法（可复用）
      that.$requestAPI(paramD).then(response => {
        this.resetcode = '1'
        var obj = JSON.parse(JSON.stringify(this.formField))
        Object.assign(obj, response.rows)
        this.formField = obj
        this.resetid += 1
      })
    },
    // 触发页面显示配置的筛选
    filterNode(value, data, node) {
      // 如果什么都没填就直接返回
      if (!value) return true
      // 如果传入的value和data中的label相同说明是匹配到了
      if (data.label.indexOf(value) !== -1) {
        return true
      }
      // 否则要去判断它是不是选中节点的子节点
      return this.checkBelongToChooseNode(value, data, node)
    },
    // 判断传入的节点是不是选中节点的子节点
    checkBelongToChooseNode(value, data, node) {
      const level = node.level
      // 如果传入的节点本身就是一级节点就不用校验了
      if (level === 1) {
        return false
      }
      // 先取当前节点的父节点
      let parentData = node.parent
      // 遍历当前节点的父节点
      let index = 0
      while (index < level - 1) {
        // 如果匹配到直接返回
        if (parentData.data.label.indexOf(value) !== -1) {
          return true
        }
        // 否则的话再往上一层做匹配
        parentData = parentData.parent
        index++
      }
      // 没匹配到返回false
      return false
    },

    handleNodeClick(menueList) {
      if (menueList.areaStockId) {
        this.areackQuery(menueList.areaStockId)
        this.editRowData = menueList.areaStockId
      } else {
        this.cityCkQuery(menueList.carStockHouseId)
      }
      this.resetid += 1
    },
    spanNum() {
      return 6
    },
    add() {
      this.dialogShow = true
    },
    close() {
      this.dialogShow = false
    },
    delete(index) {
      this.$confirm('真的要删除吗？', {
        tyep: 'warning'
      }).then(() => {
        const that = this
        const queryObj = {
        // api配置
          apiConfig: { ServiceCode: 'delRegionalCity', APIUrl: '/mp/e3sh/vesale/basics/regionalCityWMService/delRegionalCity.do' },
          // 条件/实体参数（变量），根据typeParam中的定义配置
          variables: {
            // 当前中台使用的名称有dataInfo、info，具体查看API文档
            dataInfo: { areaStockId: this.editRowData, updateControlId: this.$refs.multipleTable.list[index].updateControlId, carStockHouseId: this.$refs.multipleTable.list[index].carStockHouseId }
          }
        }
        queryObj.variables.areaStockId = this.editRowData
        // 转换了中台请求格式数据
        var paramD = that.$getParams(queryObj)
        // 调用中台API方法（可复用）
        that.$requestAPI(paramD).then(response => {
          if (response.msg) {
            this.$message({
              message: response.msg,
              type: 'warn',
              uration: 2000
            })
          }
          if (response.result === '1') {
            this.areackQuery(this.editRowData)
            this.querymenue()
          }
        })
      })
    },
    confirm(msg) {
      this.$confirm(msg)
    },
    // 网格
    // queryTable(page, dataType, size, filterObj, cb) {
    //   if (this.formField.menuId === "") {
    //     this.$message({
    //       message: this.$t("org.message.selMul") /*请选择一条数据*/,
    //       type: "warning",
    //       duration: 1000
    //     });
    //     return false;
    //   }
    //   // popups 组件弹窗  page 表单查询
    //   this.$utils.validataMoth(this, "validpage");
    //   if (this.valid) {
    //     this.$refs.multipleTable.queryTable(
    //       page,
    //       dataType,
    //       size,
    //       filterObj,
    //       cb
    //     );
    //   }
    // },
    // 树形结构
    querymenue() {
      const that = this
      const queryObj = {
        // api配置
        apiConfig: { ServiceCode: 'findTreeRegional', APIUrl: '/mp/e3sh/vesale/basics/regionalCityWMService/findTreeRegional.do' },
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          pageSize: '',
          pageIndex: '',
          // 当前中台使用的名称有dataInfo、info，具体查看API文档
          dataInfo: that.menueParam
        }
      }
      // 转换了中台请求格式数据
      var paramD = that.$getParams(queryObj)
      // 调用中台API方法（可复用）
      that.$requestAPI(paramD).then(response => {
        if (
          response.result === '1' &&
          response.rows !== ''
        ) {
          var dataList = response.rows
          var newjson = JSON.parse(JSON.stringify(dataList).replace(/areaStockName/g, 'label').replace(/city/g, 'children').replace(/carHouseName/g, 'label'))
          that.menueList = newjson
        }
      })
    }
  }
}
</script>
<style  lang="scss" scoped>
div.el-input{
    width: 90% !important;
    outline: none;
    margin:10px 5% !important;
}
#TreeTable{
  height:  100% !important;
}
/deep/ .mixButton{
  padding-top:20px;
  margin-bottom:-10px;
  margin-left:3%;
}
.tree-input{
    width: 90%;
    border: 1px solid #999;
    outline: none;
    margin:10px 5%;
}
.hander-bg{
  // height: 715px !important;
  background: white;
}

</style>
